package com.atguigu.crowd.handler;

import com.atguigu.crowd.api.MySQLRemoteService;
import com.atguigu.crowd.api.RedisRemoteService;
import com.atguigu.crowd.entity.po.MemberPO;
import com.atguigu.crowd.entity.vo.MemberLoginVO;
import com.atguigu.crowd.entity.vo.MemberVO;
import com.atguigu.crowd.util.CrowdConstant;
import com.atguigu.crowd.util.CrowdUtil;
import com.atguigu.crowd.util.ResultEntity;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpSession;
import java.util.Objects;
import java.util.concurrent.TimeUnit;

/**
 * @author yzt
 * @create 2021-09-22 21:51
 */
@Controller
public class MemberHandler {

    @Autowired
    private RedisRemoteService redisRemoteService;

    @Autowired
    private MySQLRemoteService mySQLRemoteService;


    @ResponseBody
    @RequestMapping("/auth/member/send/short/message")
    public ResultEntity<String> authMemberSendMessage(@RequestParam("phoneNum") String phoneNum){

        ResultEntity<String> shortMessageEntity = CrowdUtil.sendShortMessage(phoneNum);
        if("SUCCESS".equals(shortMessageEntity.getOperationResult())){
            String code = shortMessageEntity.getQueryData();
            String phoneKey = "CROWD_SHORT_MESSAGE_"+phoneNum;
            ResultEntity<String> redisEntity = redisRemoteService.setRedisKeyValueRemoteWithTimeout(phoneKey, code, 5, TimeUnit.MINUTES);
            if("SUCCESS".equals(redisEntity.getOperationResult())){
                return ResultEntity.successWithoutData();
            }else{
                return redisEntity;
            }
        }
        return shortMessageEntity;
    }

    @RequestMapping("/auth/do/member/register")
    public String doMemberRegister(MemberVO memberVO, Model model){
        //获取手机号
        String phoneNum = memberVO.getPhoneNum();
        //拼接key
        String redisKey = "CROWD_SHORT_MESSAGE_"+phoneNum;

        ResultEntity<String> redisEntity = redisRemoteService.getRedisStringValueByKeyRemote(redisKey);
        //判断获取是否成功
        if("FAILED".equals(redisEntity.getOperationResult())){
           model.addAttribute("message",redisEntity.getOperationMessage());
           return "member-reg";
        }
        String redisCode = redisEntity.getQueryData();
        //判断获取到的验证码是否为空
        if(redisCode == null){
            model.addAttribute("message","验证码不正确!");
            return "member-reg";
        }
        String memberVOCode = memberVO.getCode();
        //判断两个验证码是否一致
        if(!Objects.equals(redisCode,memberVOCode)){
            model.addAttribute("message","验证码不正确!");
            return "member-reg";
        }
        //若一致，则执行删除
        redisRemoteService.removeRedisKeyRemote(redisKey);

        //执行密码加密
        BCryptPasswordEncoder passwordEncoder = new BCryptPasswordEncoder();
        String encode = passwordEncoder.encode(memberVO.getUserpswd());
        memberVO.setUserpswd(encode);
        MemberPO memberPO = new MemberPO();
        BeanUtils.copyProperties(memberVO,memberPO);

        ResultEntity<String> saveMemberEntity = mySQLRemoteService.saveMember(memberPO);

        if("FAILED".equals(saveMemberEntity.getOperationResult())){
            model.addAttribute("message","出错了，请重新注册!");
            return "member-reg";
        }
        return "redirect:http://localhost/auth/member/to/login/page";
    }

    @RequestMapping("/auth/member/do/login")
    public String doLogin(@RequestParam("loginacct") String loginacct,
                          @RequestParam("userpswd") String userpswd,
                          Model model, HttpSession session){

        ResultEntity<MemberPO> resultEntity = mySQLRemoteService.getMemberPOByLoginAcctRemote(loginacct);
        if("FAILED".equals(resultEntity.getOperationResult())){
            model.addAttribute("message","该账号不存在！");
            return "member-login";
        }

        MemberPO memberPO = resultEntity.getQueryData();
        if(memberPO == null){
            model.addAttribute("message","该账号不存在！");
            return "member-login";
        }
        String userpswdDB = memberPO.getUserpswd();

        BCryptPasswordEncoder passwordEncoder = new BCryptPasswordEncoder();
        boolean matche = passwordEncoder.matches(userpswd, userpswdDB);

        if(!matche){
            model.addAttribute("message","账号或密码错误，请重新登录！");
            return "member-login";
        }

        session.setAttribute("loginMember",new MemberLoginVO(memberPO.getId(),memberPO.getUsername(),memberPO.getEmail()));
        return "redirect:http://localhost/auth/member/to/center/page";
    }

    @RequestMapping("/auth/member/to/logout")
    public String doLogout(HttpSession session){
        session.invalidate();
        return "redirect:http://localhost/";
    }
}
